cmake_minimum_required(VERSION 3.12.4)

project(openssl)

# 设置OpenSSL源码目录
set(OPENSSL_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/openssl-1.1.1w)

# 设置编译选项
set(OPENSSL_CONFIG_OPTIONS
    shared
    no-ssl3
    --prefix=${CMAKE_INTERNAL_INSTALL_PREFIX}
    --openssldir=${CMAKE_INTERNAL_INSTALL_PREFIX}
    linux-armv4
    -DL_ENDIAN
)

# 将列表转换为空格分隔的字符串
string(REPLACE ";" " " OPENSSL_CONFIG_OPTIONS_STR "${OPENSSL_CONFIG_OPTIONS}")

# 设置环境变量
set(ENV{CC} "${CMAKE_C_COMPILER}")
set(ENV{AR} "${CMAKE_AR}")
set(ENV{RANLIB} "${CMAKE_RANLIB}")
set(ENV{PATH} "${CROSS_COMPILE_PATH}:$ENV{PATH}")

# 配置OpenSSL
add_custom_command(
    OUTPUT ${OPENSSL_SOURCE_DIR}/Makefile
    COMMAND ${CMAKE_COMMAND} -E env PATH=$ENV{PATH} ./Configure linux-armv4 --cross-compile-prefix=arm-arago-linux-gnueabi- --prefix=${CMAKE_INTERNAL_INSTALL_PREFIX} --openssldir=${CMAKE_INTERNAL_INSTALL_PREFIX} shared no-ssl3 no-async -DL_ENDIAN threads -lpthread
    WORKING_DIRECTORY ${OPENSSL_SOURCE_DIR}
    COMMENT "Configuring OpenSSL"
)

# 编译OpenSSL
add_custom_command(
    OUTPUT ${OPENSSL_SOURCE_DIR}/libssl.a ${OPENSSL_SOURCE_DIR}/libcrypto.a
    COMMAND ${CMAKE_COMMAND} -E env PATH=$ENV{PATH} $(MAKE)
    DEPENDS ${OPENSSL_SOURCE_DIR}/Makefile
    WORKING_DIRECTORY ${OPENSSL_SOURCE_DIR}
    COMMENT "Building OpenSSL"
)

# 创建自定义目标
add_custom_target(openssl ALL
    DEPENDS ${OPENSSL_SOURCE_DIR}/libssl.a ${OPENSSL_SOURCE_DIR}/libcrypto.a
)

# 安装规则
add_custom_target(openssl_install
    COMMAND ${CMAKE_COMMAND} -E env PATH=$ENV{PATH} $(MAKE) install_sw
    WORKING_DIRECTORY ${OPENSSL_SOURCE_DIR}
    COMMENT "Installing OpenSSL"
    DEPENDS openssl
)

# 添加安装规则
install(DIRECTORY ${CMAKE_INTERNAL_INSTALL_PREFIX}/lib/
    DESTINATION lib
    FILES_MATCHING PATTERN "*.so*" PATTERN "*.a"
)

install(DIRECTORY ${CMAKE_INTERNAL_INSTALL_PREFIX}/include/openssl
    DESTINATION include
)

install(DIRECTORY ${CMAKE_INTERNAL_INSTALL_PREFIX}/bin/
    DESTINATION bin
    FILES_MATCHING PATTERN "openssl"
)
